import { Component, Injector, ViewEncapsulation, ViewChild, ElementRef, AfterViewInit, EventEmitter, Output, Input } from '@angular/core';
import { AppComponentBase } from '@shared/common/app-component-base';
import { LocationDto, LocationServiceProxy } from '@shared/service-proxies/service-proxies';

@Component({
  selector: 'selectLocation',
  templateUrl: './select-location.component.html',
  encapsulation: ViewEncapsulation.None
})

export class SelectLocationComponent extends AppComponentBase implements AfterViewInit {

  @ViewChild('areaCombobox') areaCombobox: ElementRef;
  @ViewChild('shelfCombobox') shelfCombobox: ElementRef;
  @ViewChild('positionCombobox') positionCombobox: ElementRef;

  _location = 0;
  @Output() locationChange = new EventEmitter();

  @Input()
  get location() {
      return this._location;
  }

  set location(val) {
      this._location = val;
      this.locationChange.emit(this._location);
  }

  areas = new Array<LocationDto>();
  shelfs = new Array<LocationDto>();
  positions = new Array<LocationDto>();

  areaId = 0;
  shelfId = 0;

  constructor(
    injector: Injector,
    private _locationServiceProxy: LocationServiceProxy,
  ) {
    super(injector);
  }

  ngAfterViewInit(): void {
    this._locationServiceProxy.getAreas()
    .subscribe(result => {
      this.areas = result.items;
      setTimeout(() => {
        $(this.areaCombobox.nativeElement).selectpicker('refresh');
      }, 0);
    });
  }

  loadShelfs() {
    this.shelfId = 0;
    this._location = 0;

    this._locationServiceProxy.getShelvesByArea(this.areaId)
      .subscribe(result => {
        this.shelfs = result.items;
        setTimeout(() => {
          $(this.shelfCombobox.nativeElement).selectpicker('refresh');
        }, 0);
      });
  }

  loadPositions() {
    this._location = 0;

    this._locationServiceProxy.getPositionsByShelf(this.shelfId)
      .subscribe(result => {
        this.positions = result.items;
        setTimeout(() => {
          $(this.positionCombobox.nativeElement).selectpicker('refresh');
        }, 0);
      });
  }

}
